package admin;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;

import com.ffpc.servlet.*;
import com.ffpc.sql.*;
import com.ffpc.struts.StrutsMessage;
import com.ffpc.util.*;
import com.system.userMultiRole.UserMultiRoleBean;
import com.system.userMultiRole.UserMultiRoleProcess;

import admin.system.sysparam.*;
import admin.system.user.UserBean;
import admin.system.user.UserProcess;
import admin.JisEncrypt;
import admin.system.passwdhistory.*;

import org.apache.regexp.RE;
 
public class UserChangePwdServlet extends DBServlet {
    
    private RE passwordComplexity1;
    private RE passwordComplexity2;
    private RE passwordComplexity3;

	@Override
	protected String perform(HttpServletRequest request, HttpServletResponse response, StrutsMessage message)
		throws  ServletException, IOException, SQLException, DataException, Exception {

            boolean debug = false;
            String sql = null;
            PreparedStatement pstmt = null;
            ResultSet resultSet = null;
            Connection conn = this.getConnection();

            String changePasswd = "Y";
            String expiryPasswd = "N";
            String tempStr = "";
            int tempInt = 0;
            Date tempDate = null;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.US);
            Calendar tempCalendar = new GregorianCalendar();

            //String action = new String(request.getParameter("formAction"));
            String action = "Update";
            if (debug) {
                System.out.println("UserChangePwdServlet.java -- action is : " + action);
            }

            //changePasswd = request.getParameter("changePasswd");
            expiryPasswd = request.getParameter("expiryPasswd");
            /*
             if (changePasswd == null) {
             changePasswd = "N";
             }
             */
            if (expiryPasswd == null) {
                expiryPasswd = "N";
            }

            UserBean user = UserProcess.createBean();
            user.setUser_id(request.getParameter("user_id"));
            //user.setUser_name(request.getParameter("user_name"));
            //user.setUser_des(request.getParameter("user_des"));

            System.out.println("conn = " + conn);
            System.out.println("user.getUser_id() = " + user.getUser_id());
            System.out.println("passwd = " + request.getParameter("passwd"));

            if (request.getParameter("oldpasswd") != null) {
                if (!(request.getParameter("oldpasswd").equals(request.getParameter("passwd")))) {
                    JisEncrypt jis_encrypt = new JisEncrypt(conn);
                    tempStr = jis_encrypt.Encrypt(request.getParameter("passwd"));
                    user.setPasswd(tempStr);
                } else {
                    user.setPasswd(request.getParameter("passwd"));
                }
            } else {
                user.setPasswd(request.getParameter("passwd"));
            }

            if (changePasswd.equals("Y") || expiryPasswd.equals("Y")) {
                SysParamBean sysParam = SysParamProcess.createBean();
                sysParam.setSys_Param_name("expiry_days");
                SysParamBean[] sysParams = SysParamProcess.find(conn, sysParam);

                if (sysParams == null || sysParams.length == 0) {
                    message.setMessage("No system parameter expiry_days, please input it.");
                    return "system/userChangePwd.jsp";
                } else {
                    tempStr = ((SysParam) sysParams[0]).getSys_Param_value();
                    tempInt = Integer.parseInt(tempStr);
                }
                tempCalendar.setTime(new Date());
                tempCalendar.add(Calendar.DAY_OF_MONTH, tempInt);
                tempStr = DateFormatter.format(tempCalendar.getTime());
                user.setPass_exp_date(tempStr);
            } else {
                SysParamBean sysParam = SysParamProcess.createBean();
                sysParam.setSys_Param_name("expiry_days");
                SysParamBean[] sysParams = SysParamProcess.find(conn, sysParam);

                if (sysParams == null || sysParams.length == 0) {
                    message.setMessage("No system parameter expiry_days, please input it.");
                    return "system/userChangePwd.jsp";
                } else {
                    tempStr = ((SysParam) sysParams[0]).getSys_Param_value();
                    tempInt = Integer.parseInt(tempStr);
                }

                Calendar expiryDate = Calendar.getInstance();
                expiryDate.add(Calendar.DAY_OF_MONTH, tempInt);
                String expiryDateStr = DateFormatter.format(tempCalendar.getTime());
                user.setPass_exp_date(expiryDateStr);

//				user.setPass_exp_date(request.getParameter("pass_exp_date"));
            }

            UserMultiRoleBean userMultiRole = UserMultiRoleProcess.createBean();

            String[] gStrRoleID = null;
            /*
             if( expiryPasswd.equals("N") ) {
             if(changePasswd.equals("N") ) {
             if(request.getParameterValues("role_id") != null) {
             gStrRoleID = request.getParameterValues("role_id");
             userMultiRole.setUser_id(request.getParameter("user_id"));
             userMultiRole.setCrt_user(getUser().getUser_id());
             userMultiRole.setCrt_date(DateFormatter.format(this.getDate()));
             userMultiRole.setUpd_user(getUser().getUser_id());
             userMultiRole.setUpd_date(DateFormatter.format(this.getDate()));
             }
             }
             }
             else {
             user.setRole_id(request.getParameter("role_id"));
             }
             */
            //user.setCost_center_id(request.getParameter("cost_center_id"));
            //user.setEmail(request.getParameter("email"));
            //user.setMobile(request.getParameter("mobile"));
            //user.setStaff_id(request.getParameter("staff_id"));
            user.setActive(request.getParameter("active"));
            user.setUpd_user(getUser().getUser_id());
            user.setUpd_date(DateFormatter.format(this.getDate()));
            //user.setInactive_date(request.getParameter("inactive_date"));
            user.setInactive_date(request.getParameter("old_inactive_date"));


//			if (request.getParameter("inactive_date")!=null) {
//				if (!(request.getParameter("inactive_date").equals(request.getParameter("old_inactive_date")))) {
//					user.setDeactivated_by(getUser().getUser_id());
//					user.setDeactivated_date(DateFormatter.format(this.getDate()));
//				}
//			}

            //user.setRequest_group(request.getParameter("request_group"));
            //user.setCompany_code(request.getParameter("company_code"));


//			user.setLogin_trial(request.getParameter("login_trial"));
            user.setLogin_trial("0");

            if (action.trim().equalsIgnoreCase("Update")) {
                final String newPassword = request.getParameter("passwd");
                if (!isPasswordComplexityEnough(newPassword)) {
                    message.setMessage("Save failure - new password must contain digits and letters of upper and lower case");
                } else {



                    if (expiryPasswd.equals("N")) {
                        System.out.println("test 1");
                        if (changePasswd.equals("N")) {
                            System.out.println("test 2");
                            /*
                             }
                             try {
                             sql = "delete from jis.jis_s_user_role where user_id = ?";
                             if(debug) System.out.println("UserChangePwdServlet.java -- del_user is : " + sql);
                             pstmt = conn.prepareStatement(sql);
                             pstmt.setString(1, userMultiRole.getUser_id());
                             pstmt.executeUpdate();
                             } catch(Exception eee) {
                             message.setMessage("Save failure.");
                             }
                             finally {
                             if (pstmt != null) pstmt.close();
                             if (conn != null) conn.close();
                             }
                             */
                            user.setCrt_user(getUser().getUser_id());
                            user.setCrt_date(DateFormatter.format(this.getDate()));

                            if (PasswdHistoryProcess.isExist(conn, user.getUser_id(), request.getParameter("passwd"))) {
                                message.setMessage("Save failure - cannot re-use latest password(s) ");
                                throw new DataException("Save failure - cannot re-use latest password(s) ");
                            }

                            if (UserProcess.delete(conn, user) > 0) {
                                if (UserProcess.insert(conn, user) > 0) {
                                    for (int i = 0; i < gStrRoleID.length; i++) {
                                        userMultiRole.setRole_id(gStrRoleID[i]);
                                        UserMultiRoleProcess.insert(conn, userMultiRole);
                                    }
                                    message.setMessage("Save successfully.");
                                } else {
                                    message.setMessage("Save failure.");
                                }
                            } else {
                                message.setMessage("Save failure.");
                            }
                        } else {
                            System.out.println("test 3");
                            if (PasswdHistoryProcess.isExist(conn, user.getUser_id(), request.getParameter("passwd"))) {
                                message.setMessage("Save failure - cannot re-use latest password(s) ");
                                throw new DataException("Save failure - cannot re-use latest password(s) ");
                            }
                            try {
                                sql = "update jis.jis_s_user set passwd = ?, pass_exp_date = to_date(?,'DD/MM/YYYY') where user_id = ?";
                                if (debug) {
                                    System.out.println("UserChangePwdServlet.java , upd_pass is : " + sql);
                                }
                                pstmt = conn.prepareStatement(sql);
                                pstmt.setString(1, user.getPasswd());
                                pstmt.setString(2, user.getPass_exp_date());
                                pstmt.setString(3, user.getUser_id());
                                pstmt.executeUpdate();

                                //PasswdHistoryProcess.updateOldestRecord(conn, user.getUser_id(), user.getPasswd(), DateFormatter.format_n(this.getDate()) );
                                PasswdHistoryProcess.updateOldestRecord(conn, user.getUser_id(), user.getPasswd(), DateFormatter.format_n(this.getDate()));
                                message.setMessage("Save sucessful.");
                            } catch (Exception eee) {
                                message.setMessage("Save failure.");
                            }
                        }
                    } else {
                        System.out.println("test 4");
                        try {
                            if (PasswdHistoryProcess.isExist(conn, user.getUser_id(), request.getParameter("passwd"))) {
                                message.setMessage("Save failure - cannot re-use latest password(s) ");
                                throw new DataException("Save failure - cannot re-use latest password(s) ");
                            }
                            sql = "update jis.jis_s_user set passwd = ?, pass_exp_date = to_date(?,'DD/MM/YYYY') where user_id = ?";
                            if (debug) {
                                System.out.println("UserChangePwdServlet.java , upd_pass is : " + sql);
                            }
                            pstmt = conn.prepareStatement(sql);
                            pstmt.setString(1, user.getPasswd());
                            pstmt.setString(2, user.getPass_exp_date());
                            pstmt.setString(3, user.getUser_id());
                            int count = pstmt.executeUpdate();

                            System.out.println("perform count=" + count + "; sql=" + sql);

                            PasswdHistoryProcess.updateOldestRecord(conn, user.getUser_id(), user.getPasswd(), DateFormatter.format_n(this.getDate()));
                            message.setMessage("Save sucessful.");
                        } catch (Exception eee) {
                            message.setMessage("Save failure.");
                        }
                    }
                }
            } else {
                message.setMessage("No action mapped!");
            }


		if ( changePasswd.equals("Y") ) {
			//return "system/ChangePassword.jsp";
			return "system/userSearchChangePwd.jsp";
		}
		else if (expiryPasswd.equals("Y")) {
			return "servlet/admin.menu.MenuServlet";
		}
		else {
			return "system/userSearchChangePwd.jsp";
		}
	}

    private boolean isPasswordComplexityEnough(String newPassword) {
        

        if (this.passwordComplexity1 == null) {
            passwordComplexity1 = new RE("\\d+");
            passwordComplexity2 = new RE("[a-z]+");
            passwordComplexity3 = new RE("[A-Z]+");
        }
        if (newPassword != null && !newPassword.trim().equals("")) {
            if (passwordComplexity1.match(newPassword)) {
                if (passwordComplexity2.match(newPassword)) {
                    if (passwordComplexity3.match(newPassword)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

